<template>
  <PageWrapper class="high-form" :title="getTitle">

    <CollapseContainer title="基础信息">
      <BasicForm @register="registerForm" ref="formRef">

        <template #managerList="{ model }">
          <BasicTable @register="registerTable1" :dataSource="model.managerList">
            <template #toolbar>
              <a-button type="primary" @click="handleCreate1"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions1(record)" />
              </template>
            </template>
          </BasicTable>
        </template>

        <template #addressList="{ model }">
          <BasicTable @register="registerTable2" :dataSource="model.addressList">
            <template #toolbar>
              <a-button type="primary" @click="handleCreate2"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions2(record)" />
              </template>
            </template>
          </BasicTable>
        </template>

        <template #bankInfoList="{ model }">
          <BasicTable @register="registerTable3" :dataSource="model.bankInfoList">
            <template #toolbar>
              <a-button type="primary" @click="handleCreate3"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="[

                  {
                    tooltip: '修改',
                    icon: 'clarity:note-edit-line',
                    onClick: handleUpdate3.bind(null, record),
                  },
                  {
                    tooltip: '删除',
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    onClick: (e) => { e.stopPropagation(); },
                    popConfirm: {
                      title: '是否确认删除',
                      confirm: handleDelete3.bind(null, record),
                      placement: 'left'
                    },
                  },
                ]" />
              </template>
            </template>
          </BasicTable>
        </template>


      </BasicForm>
    </CollapseContainer>

    <template v-if="showCommit" #rightFooter>
      <a-button @click="goback">返回列表</a-button>  <span> </span>
      <a-button type="primary" @click="handleSaveForm">保存</a-button>
    </template>

    <FormManagerModal @register="registerModal1" @managerData="getChildData1" />
    <FormAddressModal @register="registerModal2" @addressData="getChildData2" />
    <FormBankModal @register="registerModal3" @bankData="getChildData3" />

  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem, } from '/@/components/Table';
import { BasicForm, useForm } from '/@/components/Form/index';
import { CollapseContainer } from '/@/components/Container';
import { useMessage } from '/@/hooks/web/useMessage';

import { PageWrapper } from '/@/components/Page';
import { Button } from '/@/components/Button';
import { BasicUpload } from '/@/components/Upload';
import { view, add, update } from '/@/api/business/client';
import { useRoute, useRouter } from 'vue-router'
import { cloneDeep, } from 'lodash-es';
import { useModal } from '/@/components/Modal';

import FormManagerModal from './FormManagerModal.vue'
import FormAddressModal from './FormAddressModal.vue'
import FormBankModal from './FormBankModal.vue'

import { formSchema, bankInfoColumns, } from './data';



export default defineComponent({
  components: { BasicTable, TableAction, BasicUpload, FormManagerModal, FormAddressModal, FormBankModal, BasicForm, CollapseContainer, PageWrapper, Button },
  emits: ['success', 'register'],
  setup() {
    //主表单
    const [registerForm, { setFieldsValue, validate }] = useForm({
      schemas: formSchema,
      labelWidth: 100,
      showActionButtonGroup: false,
    });

    const showCommit = ref(true);//是否显示表单提交
    const { createMessage } = useMessage();
    const isUpdate = ref(false);
    const getTitle = computed(() => (!unref(isUpdate) ? '新增客户信息' : '编辑客户信息'));

    //1联系人列表
    const [registerTable1, { getDataSource: getDataSource1, insertTableDataRecord: insertTableDataRecord1,
      updateTableDataRecord: updateTableDataRecord1, deleteTableDataRecord: deleteTableDataRecord1, }] = useTable({
        columns: [{
          title: '姓名',
          dataIndex: 'name',
          editRow: true,
        }, {
          title: '职位',
          dataIndex: 'position',
          editRow: true,
        }, {
          title: '电话',
          dataIndex: 'tel',
          editRow: true,
        },],
        formConfig: {
          labelWidth: 120,
          showAdvancedButton: false,
          showResetButton: false,
          autoSubmitOnEnter: true,
        },
        canColDrag: true,
        useSearchForm: false,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          fixed: false,
        },
      });
    //联系人弹框begin
    const [registerModal1, { openModal: openModal1 }] = useModal();
    function handleCreate1() {
      openModal1(true, {
        isUpdate: false,
      });
    }
    function getChildData1(data) {
      if (data.id) {
        updateTableDataRecord1(data.id, data)
      } else {
        insertTableDataRecord1(data)
      }
    }
    //联系人弹框end

    //2地址列表
    const [registerTable2, { getDataSource: getDataSource2, insertTableDataRecord: insertTableDataRecord2,
      updateTableDataRecord: updateTableDataRecord2,
      deleteTableDataRecord: deleteTableDataRecord2, }] = useTable({
        columns: [{
          title: '名称',
          dataIndex: 'name',
          editRow: true,
        }],
        formConfig: {
          labelWidth: 120,
          showAdvancedButton: false,
          showResetButton: false,
          autoSubmitOnEnter: true,
        },
        canColDrag: true,
        useSearchForm: false,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          fixed: false,
        },
      });
    //地址弹框begin
    const [registerModal2, { openModal: openModal2 }] = useModal();
    function handleCreate2() {
      openModal2(true, {
        isUpdate: false,
      });
    }
    function getChildData2(data) {
      if (data.id) {
        updateTableDataRecord2(data.id, data)
      } else {
        insertTableDataRecord2(data)
      }
    }
    //地址弹框end

    //3开户信息列表
    const [registerTable3, { getDataSource: getDataSource3, insertTableDataRecord: insertTableDataRecord3,
      updateTableDataRecord: updateTableDataRecord3, deleteTableDataRecord: deleteTableDataRecord3, }] = useTable({
        columns: bankInfoColumns,
        formConfig: {
          labelWidth: 120,
          showAdvancedButton: false,
          showResetButton: false,
          autoSubmitOnEnter: true,
        },
        canColDrag: true,
        useSearchForm: false,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          fixed: false,
        },
      });
    //开户信息弹框begin
    const [registerModal3, { openModal: openModal3 }] = useModal();
    function handleCreate3() {
      openModal3(true, {
        isUpdate: false,
      });
    }
    function handleUpdate3(record: EditRecordRow) {
      openModal3(true, {
        record,
        isUpdate: true,
      });
    }
    function handleDelete3(record: EditRecordRow) {
      console.log('删除开票资料', record)
      deleteTableDataRecord3(record.key)
    }
    function getChildData3(data) {
      console.log('子页面数据：', data)
      if (data.id) {
        console.log('编辑开票资料', data)
        updateTableDataRecord3(data.id, data)
      } else {
        insertTableDataRecord3(data)
      }
    }
    //开户信息弹框end



    // 获取路由参数
    let id = 0
    const r = useRoute();
    let idStr = r.params.id
    if (typeof (idStr) == 'string') {
      id = parseInt(idStr, 10)
    } else {
      id = parseInt(idStr[0], 10)
    }
    if (id > 0) {
      isUpdate.value = true
      // 获取数据
      view(id).then((res: any) => {
        setFieldsValue(res);
      });
    }






    const currentEditKeyRef1 = ref('');
    //列表操作栏定义1：联系人
    function createActions1(record: EditRecordRow): ActionItem[] {
      if (!record.editable) {
        return [
          {
            tooltip: '编辑',
            icon: 'clarity:note-edit-line',
            disabled: currentEditKeyRef1.value ? currentEditKeyRef1.value !== record.key : false,
            onClick: handleEdit1.bind(null, record),
          },
          {
            tooltip: '删除',
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete1.bind(null, record),
              placement: 'left'
            },
            disabled: currentEditKeyRef1.value ? currentEditKeyRef1.value !== record.key : false,
          },
        ];
      }
      return [
        {
          label: '保存',
          onClick: handleSave1.bind(null, record),
        },
        {
          label: '取消',
          popConfirm: {
            title: '是否取消编辑',
            confirm: handleCancel1.bind(null, record),
          },
        },
      ];
    }

    function handleEdit1(record: EditRecordRow) {
      currentEditKeyRef1.value = record.key;
      record.onEdit?.(true);
    }
    function handleCancel1(record: EditRecordRow) {
      currentEditKeyRef1.value = '';
      record.onEdit?.(false, false);
    }
    function handleDelete1(record: EditRecordRow) {
      deleteTableDataRecord1(record.name)
    }
    async function handleSave1(record: EditRecordRow) {
      // 校验
      createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
      const valid = await record.onValid?.();
      if (valid) {
        try {
          const data = cloneDeep(record.editValueRefs);
          console.log(data);
          //TODO 此处将数据提交给服务器保存
          // ...
          // 保存之后提交编辑状态
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef1.value = '';
          }
          createMessage.success({ content: '数据已保存', key: 'saving' });
        } catch (error) {
          createMessage.error({ content: '保存失败', key: 'saving' });
        }
      } else {
        createMessage.error({ content: '请填写正确的数据', key: 'saving' });
      }
    }

    const currentEditKeyRef2 = ref('');
    //列表操作栏定义2: 地址
    function createActions2(record: EditRecordRow): ActionItem[] {
      if (!record.editable) {
        return [
          {
            tooltip: '编辑',
            icon: 'clarity:note-edit-line',
            disabled: currentEditKeyRef2.value ? currentEditKeyRef2.value !== record.key : false,
            onClick: handleEdit2.bind(null, record),
          },
          {
            tooltip: '删除',
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete2.bind(null, record),
              placement: 'left'
            },
            disabled: currentEditKeyRef2.value ? currentEditKeyRef2.value !== record.key : false,
          },
        ];
      }
      return [
        {
          label: '保存',
          onClick: handleSave2.bind(null, record),
        },
        {
          label: '取消',
          popConfirm: {
            title: '是否取消编辑',
            confirm: handleCancel2.bind(null, record),
          },
        },
      ];
    }

    function handleEdit2(record: EditRecordRow) {
      currentEditKeyRef2.value = record.key;
      record.onEdit?.(true);
    }
    function handleCancel2(record: EditRecordRow) {
      currentEditKeyRef2.value = '';
      record.onEdit?.(false, false);
    }
    function handleDelete2(record: EditRecordRow) {
      deleteTableDataRecord2(record.id)
    }
    async function handleSave2(record: EditRecordRow) {
      // 校验
      createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
      const valid = await record.onValid?.();
      if (valid) {
        try {
          const data = cloneDeep(record.editValueRefs);
          console.log(data);
          //TODO 此处将数据提交给服务器保存
          // ...
          // 保存之后提交编辑状态
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef2.value = '';
          }
          createMessage.success({ content: '数据已保存', key: 'saving' });
        } catch (error) {
          createMessage.error({ content: '保存失败', key: 'saving' });
        }
      } else {
        createMessage.error({ content: '请填写正确的数据', key: 'saving' });
      }
    }


    //子表格结束

    const router = useRouter();
    function goback() {
      //跳转列表页
      router.push('/report/client');
    }

    async function handleSaveForm() {
      let tableData1 = getDataSource1()
      let tableData2 = getDataSource2()
      let tableData3 = getDataSource3()

      const values = await validate();
      values.managerList = tableData1
      values.addressList = tableData2
      values.bankInfoList = tableData3
      console.log('formData=', values)

      if (unref(isUpdate)) {
        await update(values);
      } else {
        await add(values).then(res => {
          //跳转查看页
          router.push('/report/client/view/' + res.id);
        });
      }
      createMessage.success({
        content: '保存成功',
        duration: 1,
      });
    }

    return {
      registerForm, getTitle, handleSaveForm, goback, showCommit,
      registerTable1, handleCreate1, createActions1, handleEdit1, handleDelete1, handleSave1, registerModal1, getChildData1,
      registerTable2, handleCreate2, createActions2, handleEdit2, handleDelete2, handleSave2, registerModal2, getChildData2,
      registerTable3, handleCreate3, handleUpdate3, handleDelete3, registerModal3, getChildData3,
    };
  },
});
</script>
